<script setup>
import { computed } from 'vue'
import {
  CaretBottom,
  SwitchButton,
  User,
  EditPen
} from '@element-plus/icons-vue'
import avatar from '@/assets/default.png'
import {_logout} from "@/api/user";
import {useUserInfoStore} from "@/stores/userInfo";
import {useRouter, useRoute} from "vue-router";
import {ElMessage, ElMessageBox} from "element-plus";
import DynamicMenu from '@/components/DynamicMenu.vue'

const router = new useRouter()
const route = useRoute()
const userInfoStore = useUserInfoStore();

// 当前激活的菜单项（根据当前路由）
const activeMenu = computed(() => {
  return route.path
})

// 获取菜单列表
const menuList = computed(() => {
  return buildMenuTree(userInfoStore.menuList)
})

// 构建菜单树结构
const buildMenuTree = (menus) => {
  if (!menus || menus.length === 0) return []
  
  // 过滤出启用的菜单（0=启用，1=禁用）
  const enabledMenus = menus.filter(menu => menu.menuStatus === 0)
  
  // 构建树形结构
  const menuMap = {}
  const rootMenus = []
  
  enabledMenus.forEach(menu => {
    menuMap[menu.id] = { ...menu, children: [] }
  })
  
  enabledMenus.forEach(menu => {
    if (menu.parentId && menuMap[menu.parentId]) {
      menuMap[menu.parentId].children.push(menuMap[menu.id])
    } else {
      rootMenus.push(menuMap[menu.id])
    }
  })
  
  return rootMenus
}

const handleCommand = (command) => {
  if (command === 'logout') {
    ElMessageBox.confirm(
        '你确认要退出吗？',
        '温馨提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
    ).then(
        async () => {
          try {
            // 调用后端退出接口，清除服务端 Redis 中的登录信息
            await _logout()
            
            // 清空前端数据
            userInfoStore.removeUserInfo()
            localStorage.removeItem('userInfo')
            
            ElMessage.success("退出成功")
            await router.push('/login')
          } catch (error) {
            // 即使后端接口调用失败，也清除前端数据
            userInfoStore.removeUserInfo()
            localStorage.removeItem('userInfo')
            ElMessage.warning("退出登录")
            await router.push('/login')
          }
        }
    )
  } else {
    router.push('/user/' + command)
  }
}
</script>

<template>
  <el-container class="layout-container">
    <!-- 左侧菜单 -->
    <el-aside width="200px">
      <div class="el-aside__logo"></div>
      <el-menu 
        :default-active="activeMenu"
        active-text-color="#ffd04b" 
        background-color="#232323" 
        text-color="#fff"
        router
      >
        <!-- 动态菜单（根据用户权限显示） -->
        <DynamicMenu
          v-for="menu in menuList"
          :key="menu.id"
          :menu="menu"
        />
        
        <!-- 个人中心（固定显示，所有用户都可访问） -->
        <el-sub-menu index="userCenter">
          <template #title>
            <el-icon>
              <User/>
            </el-icon>
            <span>个人中心</span>
          </template>
          <el-menu-item index="/user/info">
            <el-icon>
              <User/>
            </el-icon>
            <span>基本资料</span>
          </el-menu-item>
          <el-menu-item index="/user/resetPassword">
            <el-icon>
              <EditPen/>
            </el-icon>
            <span>修改密码</span>
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-aside>
    <!-- 右侧主区域 -->
    <el-container>
      <!-- 头部区域 -->
      <el-header>
        <div>欢迎：<strong>{{ userInfoStore.userInfo.realName }}</strong></div>
        <el-dropdown placement="bottom-end" @command="handleCommand">
                    <span class="el-dropdown__box">
                        <el-avatar :src="userInfoStore.userInfo.avatar?userInfoStore.userInfo.avatar:avatar"/>
                        <el-icon>
                            <CaretBottom/>
                        </el-icon>
                    </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="info" :icon="User">基本资料</el-dropdown-item>
              <el-dropdown-item command="resetPassword" :icon="EditPen">重置密码</el-dropdown-item>
              <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-header>
      <!-- 中间区域 -->
      <el-main>
        <router-view/>
      </el-main>
      <!-- 底部区域 -->
      <el-footer>寒衣补助申请系统 ©2025 </el-footer>
    </el-container>
  </el-container>
</template>

<style lang="scss" scoped>
.layout-container {
  height: 100vh;

  .el-aside {
    background-color: #232323;

    &__logo {
      height: 120px;
      background: url('@/assets/login_title.png') no-repeat center / 120px auto;
    }

    .el-menu {
      border-right: none;
    }
  }

  .el-header {
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .el-dropdown__box {
      display: flex;
      align-items: center;

      .el-icon {
        color: #999;
        margin-left: 10px;
      }

      &:active,
      &:focus {
        outline: none;
      }
    }
  }

  .el-footer {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #666;
  }
}
</style>
